package architecture;

//_ID_ForwardingUnit
public class _ID_ForwardingUnit{
	
	MyInt EX_MEM_RegisterRd;
	MyInt EX_MEM_RegWrite;
	
	MyInt MEM_WB_RegisterRd;
	MyInt MEM_WB_RegWrite;
	
	MyInt ID_EX_RegisterRd;
	MyInt ID_EX_RegWrite;
	
	MyInt IF_ID_RegisterRt;
	MyInt IF_ID_RegisterRs;
	
	MyInt MEM_WB_MemToReg;
	
	MyInt forwardD1;
	MyInt forwardD2;
	
	boolean forwardingFailureD1;
	boolean forwardingFailureD2;
	
	MyBoolean id_is_forwarding;
	
	void setforwardD2(){
		forwardingFailureD2=false;
		forwardD2.i=0;
		
		if(EX_MEM_RegWrite.i==1
				&&IF_ID_RegisterRt.i==EX_MEM_RegisterRd.i){	
			forwardD2.i=3;
			return;
		}
		if(MEM_WB_RegWrite.i==1
				&&IF_ID_RegisterRt.i==MEM_WB_RegisterRd.i
				&&(EX_MEM_RegWrite.i!=1||
						IF_ID_RegisterRt.i!=EX_MEM_RegisterRd.i)){
			if(MEM_WB_MemToReg.i==1)
				forwardD2.i=1;
			else forwardD2.i=2;
			return;
		}
		if(ID_EX_RegWrite.i==1
				&&IF_ID_RegisterRt.i==ID_EX_RegisterRd.i){
			forwardingFailureD2=true;
			return;
		}
	}
	void setforwardD1(){
		forwardingFailureD1=false;
		forwardD1.i=0;
		
		if(EX_MEM_RegWrite.i==1
				&&IF_ID_RegisterRs.i==EX_MEM_RegisterRd.i){	
			forwardD1.i=3;
			return;
		}
		if(MEM_WB_RegWrite.i==1
				&&IF_ID_RegisterRs.i==MEM_WB_RegisterRd.i
				&&(EX_MEM_RegWrite.i!=1||
						IF_ID_RegisterRs.i!=EX_MEM_RegisterRd.i)){
			if(MEM_WB_MemToReg.i==1)
				forwardD1.i=1;
			else forwardD1.i=2;
			return;
		}
		if(ID_EX_RegWrite.i==1
				&&IF_ID_RegisterRs.i==ID_EX_RegisterRd.i){
			forwardingFailureD1=true;
			return;
		}
	}
	void clockEvent(){
		setforwardD1();
		setforwardD2();
		if(!id_is_forwarding.b){
			if(forwardD1.i!=0){
				forwardingFailureD1=true;
				forwardD1.i=0;
			}
			if(forwardD2.i!=0){
				forwardingFailureD2=true;
				forwardD2.i=0;
			}
		}
	}
	void dump(){
		System.out.println("--------");
		System.out.println("_ID_ForwardingUnit:");
		System.out.println("EX_MEM_RegisterRd:"+EX_MEM_RegisterRd);
		System.out.println("EX_MEM_RegWrite:"+EX_MEM_RegWrite);
		System.out.println("MEM_WB_RegisterRd:"+MEM_WB_RegisterRd);
		System.out.println("MEM_WB_RegWrite:"+MEM_WB_RegWrite);
		System.out.println("ID_EX_RegisterRd:"+ID_EX_RegisterRd);
		System.out.println("ID_EX_RegWrite:"+ID_EX_RegWrite);
		System.out.println("IF_ID_RegisterRt:"+IF_ID_RegisterRt);
		System.out.println("IF_ID_RegisterRs:"+IF_ID_RegisterRs);
		System.out.println("MEM_WB_MemToReg:"+MEM_WB_MemToReg);
		System.out.println("forwardD1:"+forwardD1);
		System.out.println("forwardD2:"+forwardD2);
		System.out.println("--------");
	}
}